package com.example.blog.controller;

import com.example.blog.response.CommonException;
import com.example.blog.response.ResponseModelDto;
import com.example.blog.response.ResponseModels;
import com.example.blog.util.ImgUtil;
import com.example.blog.util.MultipartFileToFile;
import com.example.blog.util.TencentUploadUtil;
import com.example.blog.util.TencentUploadUtilOld;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Admin
 */
@RestController
@Api(value = "保存图片接口", tags = "保存图片接口")
@RequestMapping("/")
public class ImgController {

//    @PostMapping("img")
//    public ResponseModelDto<String> addImg(@RequestParam(value = "file") MultipartFile file){
//        return ResponseModels.ok(ImgUtil.addImg(file,"./img/"));
//    }

    //上传图片到腾讯云的对象储存 返回url地址
    @ApiOperation(value = "上传图片返回url", notes="")
    @PostMapping("/img")
    //type为文件夹的名字
    public ResponseModelDto<String> uploadImg(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return ResponseModels.commonException("文件为空");
        }
        //2.调用方法，传入要在服务器上保存的目录及文件名 和 文件
        String fileName = "gzzp/"+System.currentTimeMillis()+file.getOriginalFilename();
        String url = TencentUploadUtil.uploadFile(fileName, MultipartFileToFile.multipartFileToFile(file));
//        System.out.println(url);
        if(url == null){
            return ResponseModels.commonException("上传失败!");
        }
        return ResponseModels.ok(url);
    }

}
